package com.scalar.chiptrack.adaptor.ikanos.tsmc;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.FabSortLot;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.dao.FabSortAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 7 Dec, 2009
 * Time: 2:05:35 PM
 */
public class TSMCPOP3DataParser extends JobHandler implements AdaptorConstants
{
    private static Logger m_parserLogger    = null;
    private String m_dataOutputDir          = null;

    private HashMap<String,FabSortLot> m_fabWipDataMap  = new HashMap<String,FabSortLot>();
    private HashMap<String,ShippedLot> m_fabShipDataMap = new HashMap<String,ShippedLot>();

    public TSMCPOP3DataParser() throws ScalarException
    {
        try
        {    m_dataOutputDir = AdaptorUtils.getDataOutputDir( VENDOR_NAME_CNX_TSMC, WIP_TYPE_FAB );
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );

            m_parserLogger = AdaptorUtils.getDataParserLogger( m_dataOutputDir, VENDOR_NAME_CNX_TSMC );
            FabSortAdaptorDAO.setLogger( m_parserLogger );
            ShippedLotDAO.setLogger( m_parserLogger );
            AdaptorUtils.setLogger( m_parserLogger );
        }
        catch ( ScalarException se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading "+VENDOR_NAME_CNX_TSMC+" WIP output directory details from database, Exception: " + se );
            throw se;
        }
    }

    public static void main( String args[] ) throws Exception
    {
        try
        {
            new TSMCPOP3DataParser().execute();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void execute() throws Exception
    {
        //Print the header details
        AdaptorUtils.printHeader(VENDOR_NAME_CNX_TSMC, CONSTANT_PARSER);

        File doneDestDir = new File(  m_dataOutputDir + "/done" );

        File sourceDataoutDir = new File( m_dataOutputDir );

        File[] fileList = sourceDataoutDir.listFiles();
        if ( ( fileList == null ) || ( fileList.length <= 3 ) )
        {
            log( "No file found in directory: " + sourceDataoutDir );
            throw new ScalarException( "\n+-----------No file found in directory " + sourceDataoutDir );
        }

        ArrayList<File> successFileList   = new ArrayList<File>();
        boolean success;

        try
        {              
            for(File file : fileList ) //for ( int i = 0; i < fileList.length; i++ )
            {
                if ( file.isDirectory() )
                {
                    continue;
                }

               if ( ( file.getName() != null ) && ( file.getName().trim().startsWith( TSMCPOP3Adaptor.FILE_NAME_WIP ) ) )
                {
                    try
                    {
                        parseWipReport ( file.getAbsolutePath() );

                        successFileList.add( file );
                        success = true;
                    }
                    catch ( Exception e )
                    {
                        success = false;
                        log( "Exception while parsing and storing file: " + file.getAbsolutePath() + "\nException: " + e );
                        e.printStackTrace();
                        throw e;
                    }
                }
            }
        }
        catch ( Exception e )
        {
            success = false;
            //log( "ERROR!! ERROR!! ERROR!! While parsing and storing File " + e );
            e.printStackTrace();
            throw e;
        }
        // to save the Fab lot tables
        try
        {
            if ( m_fabWipDataMap.isEmpty() == false )
            {
                log( "Updating Fab Lot Information" );
                FabSortAdaptorDAO.saveFabLot( null,  m_fabWipDataMap.values().iterator(), WIP_TYPE_FAB, VENDOR_NAME_CNX_TSMC );
            }
            else
            {
                System.out.println( "This is FAB Data Parser FAB Part Number List is empty" );
                FabSortAdaptorDAO.closeFabSortLot( null, WIP_TYPE_FAB, VENDOR_NAME_CNX_TSMC );
            }
            success = true;
        }
        catch ( Exception e )
        {
            success = false;
            log( "ERROR!! ERROR!! ERROR!! Could not update Fab Data information into database: " + e );
            e.printStackTrace();
            throw e;
        }

        try
        {
            // Save shipping info -
            if ( m_fabShipDataMap.isEmpty() == false )
            {
                log( "Updating shipment Information" );
                ShippedLotDAO.saveShippedLot( null, m_fabShipDataMap.values().iterator() );
            }
            success = true;
        }
        catch ( Exception e )
        {
            success = false;
            log( "ERROR!! ERROR!! ERROR!! Could not update CNXT TSMC Fab Shipping information into database: " + e );
            e.printStackTrace();
            throw e;
        }

        // To Close the Drop Out Lots
        AdaptorDAO.closeDropOutLots( VENDOR_NAME_CNX_TSMC );

        // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
        AdaptorDAO.sendAllNotifications( VENDOR_NAME_CNX_TSMC, true, true, true );

        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( TSMCPOP3Adaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);

        // Update Adaptor_Run_Info table
        try
        {
            if ( success )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, TSMCPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
        }
        catch ( ScalarException se )
        {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, TSMCPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
        }
        // Move the successful files to 'done' directory
       if ( success )
       {
           AdaptorUtils.moveFilesToDone( successFileList, doneDestDir );
       }
    }//end of execute method

    private void parseWipReport( String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result     = null;
        String partNumber       = null;
        String lotNumber        = null;
        FabSortLot fabSortLot   = null;
        try
        {
            File wipFile = new File( fileName );
            if ( !wipFile.exists() )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "Parsing the file for Wip Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "Parsing the file for Wip Report..." );

            Parser parser = ParserFactory.getXLSParser( wipFile , "TSMC WIP" );

            ((XLSParserImpl)parser).setHeaderRowIdx(0);
            ((XLSParserImpl)parser).setDataStartRowIdx(1);

            result = parser.parse();

            while ( result.next() )
            {
                partNumber = result.getString("CNXT part #");
                lotNumber = result.getString("Lot #");

                if ( partNumber != null && partNumber.trim().length()> 0 && lotNumber != null&& lotNumber.trim().length() > 0 )
                {
                    fabSortLot = m_fabWipDataMap.get( partNumber + lotNumber );
                    if ( fabSortLot == null )
                    {
                        fabSortLot = new FabSortLot(VENDOR_NAME_CNX_TSMC, WIP_TYPE_FAB );
                        m_fabWipDataMap.put( partNumber + lotNumber , fabSortLot );
                    }

                    int quantity = 0;
                    if ( fabSortLot.getQtyIn() != null )
                    {
                        try
                        {
                            quantity = Integer.parseInt( fabSortLot.getQtyIn() );
                        }
                        catch ( NumberFormatException ignore )
                        {
                        }
                        quantity += result.getInt("Current qty");
                    }
                    else
                    {
                       quantity = result.getInt("Current qty");
                    }

                    if ( quantity > 0 )
                    {
                        fabSortLot.setLotId( lotNumber );
                        fabSortLot.setCustProduct( partNumber );
                        fabSortLot.setDateIn(StringUtils.formatDateToString(result.getDate("Start Date") ) );
                        fabSortLot.setQtyIn( quantity +"");
                        fabSortLot.setStage( result.getString("Stage") );
                        fabSortLot.setFabLotNumber( lotNumber );
                        fabSortLot.setWsQty ( result.getInt("Start qty")+"");
                        fabSortLot.setLotCategory( LOT_CATEGORY_TYPE_PROD );
                        fabSortLot.setPoNumber(result.getString("PO"));
                        fabSortLot.setForcastedDateOut(StringUtils.formatDateToString(result.getDate("POD") ) );
                        fabSortLot.setShip_fcst_date(StringUtils.formatDateToString(result.getDate("Commit") ));
                        fabSortLot.setFabLotNumber( lotNumber );
                        fabSortLot.setLotStatus( LOT_STATUS_RUNNING );
                    }
                }
            }// END OF WHILE
        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
            throw ex;
        }
    } // end of prase parseWipReport method

    private static void log( String message )
    {
        if ( message == null ) return;

        if ( m_parserLogger != null )
        {
            synchronized ( m_parserLogger )
            {
                m_parserLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}
